package servlet;
import model.Department;
import model.PageModel;
import org.apache.commons.beanutils.BeanUtils;
import tools.IODataTool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.rowset.serial.SerialException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@WebServlet("/department/*")
// /department  窄化路径
public class DepartmentServlet extends HttpServlet {

    // 操作无非就是 crud  doGet doPost doPut doDelete
    // 声明一个入口(公有的方法)
    public void main(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        // 1.设置编码字符集
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        StringBuffer requestURL = req.getRequestURL();
        System.out.println(requestURL);
        // 2. 接收请求路径
        String uri = req.getRequestURI();// uri /day38/
        if (uri.contains("addDepartment.action")){
            addDepartment(req,resp);
        } else if (uri.contains("toEditDepartment.action")) {
            toEditDepartment(req,resp);
        } else if (uri.contains("editDepartment.action")) {
            editDepartment(req,resp);
        } else if (uri.contains("deleteDepartment.action")) {
            deleteDepartment(req,resp);
        } else if (uri.contains("listDepartments.action")) {
            listDepartments(req,resp);
        } else if (uri.contains("fuzzyQueryDepartment.action")){
            fuzzyQueryDepartments(req,resp);
        } else if (uri.contains("batchDeleteDepartment.action")) {
            batchDeleteDepartment(req,resp);
        } else if (uri.contains("pageQueryDepartments.action")) {
            pageQueryDepartments(req,resp);
        }else if (uri.contains("pageQueryDepart2ments.action")) {
            pageQueryDepart2ments(req,resp);
        }

    }
    /*
         分页对象： 当前页 起始页  结束页  每页的数据(List)---size(固定值)  分页页码数量 总的页码数  总的条目数
       */
    // 分页查询  handle处理器 接口
    private void pageQueryDepartments(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException{
        String currentPage = req.getParameter("currentPage");
        // 对当前页进行初始化
        currentPage = currentPage == null ? "1": currentPage;
        // 转化成int类型
        int nowPage = Integer.parseInt(currentPage);
        //private Integer totalPage;// 总的页码数  totalPage=  Math.ceil(totalCount/size)   size = 3
        //    private Integer totalCount;// 总的条目数  size
        List<Department> departmentList = IODataTool.readData();
        // 准备一个空容器
        List<Department> pageList = new ArrayList<>();
        // 先进行为空校验
        if (departmentList == null || departmentList.size() == 0) {
            req.getSession().setAttribute("page", null);
        } else {
            int totalCount = departmentList.size();
            int totalPage = (int)Math.ceil(totalCount/3.0);
            //每页需要展示的数据 size = 3  departmentList
            // currentPage=1  准备一个空容器  (currentPage-1)*size  遍历添加 count++  count==3
            int count = 0;
            for (int i = (nowPage-1) * 3; i < departmentList.size() && count < 3; i++) {// 0 1 2 3
                count++;
                pageList.add(departmentList.get(i));
            }
            // 构建分页对象
            PageModel<Department> page = new PageModel<>(nowPage, pageList, totalPage, totalCount);
            req.getSession().setAttribute("page", page);
        }
        // 跳转到listDepartment.jsp页面上
        resp.sendRedirect(req.getContextPath() + "/listDepartment.jsp");
    }

    // 批量删除
    private void batchDeleteDepartment(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException{
        String[] checkIds = req.getParameterValues("checkId");
        for (int i = 0; i < checkIds.length; i++) {
            // 调用IO流删除对应的部门对象信息
            IODataTool.writeData(new Department(checkIds[i]), "delete");
        }
        // 重定向到查询部门列表请求中
        resp.sendRedirect(req.getContextPath() + "/department/pageQueryDepartments.action");
    }

    // 模糊查询
    private void fuzzyQueryDepartments(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException{
        String searchKeyword = req.getParameter("searchKeyword");
        String searchKeyField = req.getParameter("searchKeyField");
        System.out.println("");
        // 通过IO流先把数据读进程序中
        List<Department> departmentList = IODataTool.readData();
        // 准备一个空容器
        List<Department> contents = new ArrayList<>();
        // 转换时间格式
        // 遍历list列表
        for (int i = 0; i < departmentList.size(); i++) {
            switch (searchKeyField) {
                case "dName":
                    if (departmentList.get(i).getdName().contains(searchKeyword)){
                        contents.add(departmentList.get(i));
                    }
                    break;
                case "dDesc":
                    if (departmentList.get(i).getdDesc().contains(searchKeyword)){
                        contents.add(departmentList.get(i));
                    }
                    break;
                case "dTime":
                    if (departmentList.get(i).getdTime().toString().equals(searchKeyword)){
                        contents.add(departmentList.get(i));
                    }
                    break;
                default:
                    break;
            }
        }
        // 往页面传输数据
        req.getSession().setAttribute("departmentList", contents);
        resp.sendRedirect(req.getContextPath() + "/department/pageQueryDepart2ments.action");


    }
    private void pageQueryDepart2ments(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException{
        String currentPage = req.getParameter("currentPage");
           List<Department> departmentList = (List<Department>) req.getSession().getAttribute("departmentList");
        // 对当前页进行初始化
        currentPage = currentPage == null ? "1": currentPage;
        // 转化成int类型
        int nowPage = Integer.parseInt(currentPage);
        //private Integer totalPage;// 总的页码数  totalPage=  Math.ceil(totalCount/size)   size = 3
        //    private Integer totalCount;// 总的条目数  size
//        List<Department> departmentList = departmentList1;
        // 准备一个空容器
        List<Department> pageList = new ArrayList<>();
        // 先进行为空校验
        if (departmentList == null || departmentList.size() == 0) {
            req.getSession().setAttribute("page", null);
        } else {
            int totalCount = departmentList.size();
            int totalPage = (int)Math.ceil(totalCount/3.0);
            //每页需要展示的数据 size = 3  departmentList
            // currentPage=1  准备一个空容器  (currentPage-1)*size  遍历添加 count++  count==3
            int count = 0;
            for (int i = (nowPage-1) * 3; i < departmentList.size() && count < 3; i++) {// 0 1 2 3
                count++;
                pageList.add(departmentList.get(i));
            }
            // 构建分页对象
            PageModel<Department> page = new PageModel<>(nowPage, pageList, totalPage, totalCount);
            req.getSession().setAttribute("page", page);
        }
        // 跳转到listDepartment.jsp页面上
        resp.sendRedirect(req.getContextPath() + "/mohuchaxunfenye.jsp");
    }
    // 部门列表
    private void listDepartments(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException{
        // 借助于IO流
        // 读数据
        List<Department> departmentList = IODataTool.readData();
        System.out.println("======"+departmentList);
        req.getSession().setAttribute("departmentList",departmentList);
        // 跳转到部门列表界面
        resp.sendRedirect(req.getContextPath()+"/listDepartment.jsp");
    }

    // 删除部门
    private void deleteDepartment(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException{
        ///department/deleteDepartment.action?id=${department.dId}
        String id = req.getParameter("id");
        IODataTool.writeData(new Department(id),"delete");
        // 重定向到部门列表请求中
        resp.sendRedirect(req.getContextPath() + "/department/pageQueryDepartments.action");

    }

    // 编辑部门
    private void editDepartment(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException{
        // 编辑部门信息
        Department d = new Department();
        try {
            BeanUtils.populate(d,req.getParameterMap());
            d.setdTime(new Date());
            // 调用IO流的write方法
            IODataTool.writeData(d,"edit");
        } catch (Exception e) {}
        // 跳转到查询部门列表请求中
        resp.sendRedirect(req.getContextPath() + "/department/pageQueryDepartments.action");
    }

    // 跳转到编辑页面
    private void toEditDepartment(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException{
        // /department/toEditDepartment.action?id=${department.dId}
        String id = req.getParameter("id");
        // 从流中读取数据
        List<Department> departmentList = IODataTool.readData();
        Department department = null;
        for (int i = 0; i < departmentList.size(); i++) {
            if (departmentList.get(i).getdId().equals(id)) {
                department = departmentList.get(i);
            }
        }
        req.getSession().setAttribute("department", department);
        // 跳转到编辑页面
        resp.sendRedirect(req.getContextPath() + "/editDepartment.jsp");

    }

    // 添加部门
    private void addDepartment(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException{
        // 获取表单数据 BeanUtils
        Department d = new Department();
        try {
            BeanUtils.populate(d, req.getParameterMap());
            // id是随机生成的
            d.setdId(UUID.randomUUID().toString().replace("-", ""));

            // date设置为当前最新时间
            d.setdTime(new Date());
            System.out.println("-----"+d);
        } catch (Exception e) {}
        // 把添加的部门对象写入到department.txt文件中
        IODataTool.writeData(d, "add");// 传入一个操作符add
        // 响应客户端 重定向到查询部门列表请求中
        resp.sendRedirect(req.getContextPath() + "/department/pageQueryDepartments.action");
    }




    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        main(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        main(req, resp);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        main(req, resp);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        main(req, resp);
    }
}
